#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include "contacts.pb.h"
#include <google/protobuf/any.h>
using namespace std;


void AddPeopleInfo(contacts::PeopleInfo* peoples) {
    cout << "----------------请新增联系人----------------" << endl;
    cout << "请输入联系人姓名: ";
    string name;
    getline(cin, name);
    peoples->set_name(name);
    cout << "请输入联系人年龄: ";
    int age;
    cin >> age;
    peoples->set_age(age);
    cin.ignore(256, '\n'); // 需要先清除缓冲区里的内容，因为我们每次在键盘输入的时候其实还敲了一个回车(\r\n)， 这是在缓冲区里面没拿走的
    for (int i = 0; ; i++) {
        cout << "请输入联系人电话" << i + 1 << "(只输入回车完成电话新增): ";
        string phone_number;
        getline(cin, phone_number);
        if (phone_number.empty()) {
            break;
        }
        // 新增电话 
        contacts::PeopleInfo_Phone* phone = peoples->add_phone_numbers();
        phone->set_number(phone_number);
        cout << "请选择电话类型(1.移动电话  2.固定电话): ";
        int type = 0;
        cin >> type;
        cin.ignore(256, '\n');
        if (type == 1) {
            phone->set_type(contacts::PeopleInfo_Phone_PhoneType::PeopleInfo_Phone_PhoneType_MP);
        } else if (type == 2) {
            phone->set_type(contacts::PeopleInfo_Phone_PhoneType::PeopleInfo_Phone_PhoneType_TEL);
        } else {
            phone->set_type(contacts::PeopleInfo_Phone_PhoneType::PeopleInfo_Phone_PhoneType_MP);
        }

    }

    // 输入联系人的地址信息
    // 先定义一个地址对象
    contacts::Address addr;
    cout << "请输入联系人家庭地址: ";
    string home_addr;
    getline(cin, home_addr);
    addr.set_home_address(home_addr);
    cout << "请输入联系人单位地址: ";
    string unit_addr;
    getline(cin, unit_addr);
    addr.set_unit_address(unit_addr);
    // 将Adress对象转化成Any对象
    peoples->mutable_data()->PackFrom(addr);
    google::protobuf::Any * data = peoples->mutable_data();
    data->PackFrom(addr);


    
    cout << "---------------新增联系人成功---------------" << endl;

}


int main() {
    contacts::contact cont;
    // 如果已经有本地文件，先从本地文件中读取信息，添加到通讯录中
    // 先打开文件
    fstream input("contacts.txt", ios::in | ios::binary);
    if (!input) {
        cout << "not fuound contacts.txt, create new file" << endl;
    } else {
        // 读取已存在的文件, 并且反序列化到内存中的通讯录对象中
        if (!cont.ParseFromIstream(&input)) {
            cerr << "反序列化失败" << endl;
            input.close();
            return -1;
        }
    }
    // 向通讯录中添加几个联系人
    
    AddPeopleInfo(cont.add_contacts());

    // 将通讯录信息写入本地文件中
    fstream output("contacts.txt", ios::out | ios::trunc | ios::binary );
    if (!output.is_open()) {
        cerr << "open contacts.txt fail" << endl;
        return -1;
    }
    if (!cont.SerializeToOstream(&output)) {
        cerr << "序列化写入文件失败" << endl;
        input.close();
        output.close();
        return -1;
    }
    cout << "写入文件成功" << endl;  
    input.close();
    output.close();    
    return 0;
}